<template>
    <div class="container" style="overflow: auto;min-height: 100vh; width: 1200px;margin: 0 auto;">
        <div class="button-container">
            <el-button @click="goBack"><i class="el-icon-back"> 返回</i></el-button>
            <span>
                <el-button v-if="!isView" @click="addItem"><i class="el-icon-plus"> 新增调动人员</i></el-button>
                <el-button v-if="!isView" type="primary" @click="saveData"><i class="el-icon-check"> 保存</i></el-button>
                <el-button @click="goToList"><i class="el-icon-s-grid"> 列表</i></el-button>
                <el-button v-if="!isView" type="danger" @click="deleteSelected"><i class="el-icon-delete">
                        删除选中</i></el-button>
                <el-button v-if="!isView" type="info" @click="printForm"><i class="el-icon-printer"> 打印</i></el-button>
            </span>
        </div>

        <div id="form">
            <h2>员工内部调动审批表</h2>
            <el-table :data="formData.transferDetails" border style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column class-name="selection" v-if="!isView" type="selection" width="55">
                </el-table-column>
                <el-table-column label="序号" type="index" width="50" align="center" />
                <el-table-column label="工号" width="120">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.employeeId" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="姓名" width="120">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.name" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="原部门/组别">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.originalDepartment" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="原职位">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.originalPosition" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="新部门/组别">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.newDepartment" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="新职位">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.newPosition" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="正式调动日期" width="280px">
                    <template slot-scope="scope">
                        <el-date-picker v-model="scope.row.transferDate" type="datetime" placeholder="选择日期时间"
                            :disabled="isView">
                        </el-date-picker>
                    </template>
                </el-table-column>
            </el-table>

            <el-form :model="formData" label-width="150px" label-position="left" class="mt-20">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="调出单位主管意见 :">
                            <el-input v-model="formData.transferOutOpinion" type="textarea"
                                :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="调出单位主管姓名 :">
                            <el-input v-model="formData.transferOutName" :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="调出单位签字日期 :">
                            <el-date-picker v-model="formData.transferOutDate" type="datetime" placeholder="选择日期时间"
                                :disabled="isView">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="接收单位主管意见 :">
                            <el-input v-model="formData.transferInOpinion" type="textarea"
                                :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="接收单位主管姓名 :">
                            <el-input v-model="formData.transferInName" :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="接收单位签字日期 :">
                            <el-date-picker v-model="formData.transferInDate" type="datetime" placeholder="选择日期时间"
                                :disabled="isView">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="部长/总监意见 :">
                            <el-input v-model="formData.directorOpinion" type="textarea" :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="部长/总监姓名 :">
                            <el-input v-model="formData.directorName" :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="部长/总监签字日期 :">
                            <el-date-picker v-model="formData.directorDate" type="datetime" placeholder="选择日期时间"
                                :disabled="isView">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="企业管理部核准意见:">
                            <el-input v-model="formData.hrApproval" type="textarea" :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="企业管理部核准人 :">
                            <el-input v-model="formData.hrName" :disabled="isView"></el-input>
                        </el-form-item>
                        <el-form-item label="企业管理部核准日期:">
                            <el-date-picker v-model="formData.hrDate" type="datetime" placeholder="选择日期时间"
                                :disabled="isView">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <p style="display: flex;justify-content: space-between;color:#757575;font-size:0.8em;padding-bottom: 20px;">
                <span>表单编号及版本：
                    AM-JY-125
                    B/1</span>
                <span>保存期限：长期</span>
            </p>
        </div>
    </div>
</template>

<script>
import { getTransferById, saveTransfer } from '@/api/transfer'
import { formatDateTime, DATE_FORMAT } from '@/utils/date'

export default {
    data() {
        return {
            formData: {
                transferDetails: [this.getEmptyDetail()],
                transferOutOpinion: '',
                transferOutName: '',
                transferOutDate: null,
                transferInOpinion: '',
                transferInName: '',
                transferInDate: null,
                directorOpinion: '',
                directorName: '',
                directorDate: null,
                hrApproval: '',
                hrName: '',
                hrDate: null
            },
            selectedRows: [],
            isView: false,
            isEdit: false,
            id: null
        };
    },
    created() {
        const { id, type } = this.$route.query;
        this.id = id;
        this.isView = type === 'view';
        this.isEdit = type === 'edit';

        if (id) {
            this.fetchData();
        }
    },
    methods: {
        getEmptyDetail() {
            return {
                employeeId: '',
                name: '',
                originalDepartment: '',
                originalPosition: '',
                newDepartment: '',
                newPosition: '',
                transferDate: null
            };
        },
        async fetchData() {
            try {
                const response = await getTransferById(this.id);
                if (response.data) {
                    // 格式化表格中的日期
                    response.data.transferDetails.forEach(item => {
                        if (item.transferDate) {
                            item.transferDate = formatDateTime(item.transferDate, DATE_FORMAT);
                        }
                    });
                    // 格式化表单中的日期
                    if (response.data.transferOutDate) {
                        response.data.transferOutDate = formatDateTime(response.data.transferOutDate, DATE_FORMAT);
                    }
                    if (response.data.transferInDate) {
                        response.data.transferInDate = formatDateTime(response.data.transferInDate, DATE_FORMAT);
                    }
                    if (response.data.directorDate) {
                        response.data.directorDate = formatDateTime(response.data.directorDate, DATE_FORMAT);
                    }
                    if (response.data.hrDate) {
                        response.data.hrDate = formatDateTime(response.data.hrDate, DATE_FORMAT);
                    }
                    this.formData = response.data;
                }
            } catch (error) {
                this.$message.error('获取数据失败');
            }
        },
        validateData() {
            let isValid = true;
            const details = this.formData.transferDetails || [];
            details.forEach((item, index) => {
                if (!item.employeeId || !item.name || !item.originalDepartment || !item.newDepartment) {
                    this.$message.error(`第${index + 1}行的工号、姓名、原部门和新部门为必填项`);
                    isValid = false;
                }
            });
            if (!this.formData.transferOutName || !this.formData.transferInName) {
                this.$message.error('调出单位主管和接收单位主管姓名为必填项');
                isValid = false;
            }
            return isValid;
        },
        async saveData() {
            if (!this.validateData()) {
                return;
            }
            try {
                // 确保保存时日期格式正确
                const formDataToSave = {
                    ...this.formData,
                    transferDetails: this.formData.transferDetails.map(item => ({
                        ...item,
                        transferDate: item.transferDate ? formatDateTime(item.transferDate, DATE_FORMAT) : null
                    })),
                    transferOutDate: this.formData.transferOutDate ? formatDateTime(this.formData.transferOutDate, DATE_FORMAT) : null,
                    transferInDate: this.formData.transferInDate ? formatDateTime(this.formData.transferInDate, DATE_FORMAT) : null,
                    directorDate: this.formData.directorDate ? formatDateTime(this.formData.directorDate, DATE_FORMAT) : null,
                    hrDate: this.formData.hrDate ? formatDateTime(this.formData.hrDate, DATE_FORMAT) : null
                };
                await saveTransfer(formDataToSave);
                this.$message.success('保存成功');
                this.$router.push('/main/renshi/renshizhidu/neibudiaodong/neibudiaodongList');
            } catch (error) {
                this.$message.error('保存失败');
            }
        },
        goBack() {
            this.$router.push('/main/renshi/renshidiaodong');
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/neibudiaodong/neibudiaodongList');
        },
        addItem() {
            this.formData.transferDetails = this.formData.transferDetails || [];
            this.formData.transferDetails.push(this.getEmptyDetail());
        },
        handleSelectionChange(val) {
            this.selectedRows = val;
        },
        deleteSelected() {
            if (this.selectedRows.length === 0) {
                this.$message.warning('请选择要删除的记录');
                return;
            }
            this.formData.transferDetails = this.formData.transferDetails.filter(
                item => !this.selectedRows.includes(item)
            );
            if (this.formData.transferDetails.length === 0) {
                this.formData.transferDetails.push(this.getEmptyDetail());
            }
        },
        printForm() {
            window.print();
        }

    }
};
</script>

<style scoped>
.button-container {
    margin: 20px;
    text-align: right;
    display: flex;
    justify-content: space-between;
}

.mt-20 {
    margin-top: 20px;
}

.el-col-12 {
    width: 50%;
    text-align: left;
}

.el-row {
    display: flex;
    justify-content: space-between;
}

::v-deep textarea.el-textarea__inner {
    resize: none;
    border: none;
    width: 80%;
}

::v-deep input.el-input__inner {
    resize: none;
    border: none;
    width: 80%;
}

@media print {
.container{
    width: 100%;
}
    .button-container {
        display: none;
    }

    ::v-deep textarea.el-textarea__inner {
        display: none;
        resize: none;
    }

    ::v-deep .selection,
    ::v-deep .el-table__header-wrapper colgroup col:first-child,
    ::v-deep .el-table__body-wrapper colgroup col:first-child {
        display: none;
    }
}
</style>